//
//  YKSVideoLive.m
//  SoundLive
//
//  Created by macintosh on 16/8/9.
//  Copyright © 2016年 Yue Shen. All rights reserved.
//

#import "YKSVideoLive.h"
#import "YKSVideoView.h"
#import "YKSHomeTableViewCell.h"
#import "YKSSoundLive.h"
#import "YKSLiveSyncInfo.h"

@interface YKSVideoLive () <UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet YKSVideoView *videoView;
@property (strong, nonatomic) IBOutlet UILabel *listTitle;
@property (strong, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic) UIInterfaceOrientationMask orientation;
@property (nonatomic, strong) NSArray *liveInfos;

@end

@implementation YKSVideoLive

#pragma mark - life cycle

- (instancetype)init
{
    if (self = [super init]) {
        [self fetchInfosFromPlist];
    }
    return self;
}

- (void)dealloc
{
    [self removeNotification];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self configVideoLive];
    [self configListTitle];
    [self configTableView];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES];
    [self addNotification];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO];
    [self removeNotification];
}

- (void)initProperty
{
    _orientation = UIInterfaceOrientationMaskPortrait;
}

- (BOOL)prefersStatusBarHidden
{
    return NO;
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)fetchInfosFromPlist
{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"source" ofType:@"plist"];
    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
    _liveInfos = dict[@"data"];
    _currentIndex = 0;
}

- (void)configVideoLive
{
    _videoView.frame = CGRectMake(0, 0, self.view.width, self.view.width / 16 * 9);
    
    NSString *fileName = _liveInfos[_currentIndex][@"playUrl"];
    NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
    NSURL *url = [NSURL URLWithString:path];
    [_videoView setContentURL:url];
    
    @weakify(self);
    _videoView.backClickedBlock = ^ {
        @strongify(self);
        [self.navigationController popViewControllerAnimated:YES];
    };
    
    _videoView.switchClickedBlock = ^ {
        @strongify(self);
        YKSSoundLive *soundLive = [[YKSSoundLive alloc] init];
        
        YKSLiveSyncInfo *syncInfos = [[YKSLiveSyncInfo alloc] init];
        syncInfos.currentIndex = self.currentIndex;
        syncInfos.seekTime = [self.videoView currentTime];
        syncInfos.isPlaying = [self.videoView isPlaying];
        
        soundLive.syncInfos = syncInfos;
        soundLive.liveInfos = self.liveInfos;
        
        [self.navigationController pushViewController:soundLive animated:YES];
    };
}

- (void)configListTitle
{
    self.listTitle.text = @"热门直播";
    [self.listTitle sizeToFit];
    self.listTitle.left = 10;
    self.listTitle.top = self.videoView.bottom + 20;
}

- (void)configTableView
{
    self.tableView.frame = CGRectMake(0, self.listTitle.bottom + 10, self.view.width, self.view.height - self.listTitle.bottom - 10)
    ;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.estimatedRowHeight = 88;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.backgroundColor = GRAYCOLOR;
    [self.tableView registerClass:[YKSHomeTableViewCell class] forCellReuseIdentifier:@"cell"];
}

#pragma mark - notification

- (void)addNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(becomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resignActive) name:UIApplicationWillResignActiveNotification object:nil];
}

- (void)removeNotification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)becomeActive
{
    if ([_videoView isPlaying]) {
        [_videoView play];
    }
}

- (void)resignActive
{
    if ([_videoView isPlaying]) {
        [_videoView pause];
    }
}

#pragma mark - screen rotation

- (void)removeOtherViewsButVideoView
{
    [_listTitle removeFromSuperview];
    [_tableView removeFromSuperview];
}

- (void)addRemovedViews
{
    [self.view insertSubview:_listTitle belowSubview:_videoView];
    [self.view insertSubview:_tableView belowSubview:_videoView];
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return _orientation > 0 ? _orientation : UIInterfaceOrientationMaskAll;
}

- (BOOL)shouldAutorotate
{
    return YES;
}

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    
    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
        if (size.width > size.height) { // 转到全屏
            _videoView.frame = CGRectMake(0, 0, size.width, size.height);
        } else { // 转回小屏
            [self addRemovedViews];
            _videoView.frame = CGRectMake(0, 0, size.width, size.width / 16 * 9);
        }
    } completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
        if (size.width > size.height) { // 转到全屏
            [self removeOtherViewsButVideoView];
        }
    }];
}

//iOS2_0-8_0
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    if (toInterfaceOrientation == UIInterfaceOrientationPortrait) { // 转回小屏
        if (self.view.bounds.size.height < self.view.bounds.size.width) {
            [self addRemovedViews];
            _videoView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.width / 16 * 9);
        }
    } else { // 转到全屏
        _videoView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
        [self removeOtherViewsButVideoView];
    }
}

#pragma mark - table delegate & datasourc
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_liveInfos count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YKSHomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    [cell setDataWithDict:_liveInfos[indexPath.row]];
    return  cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (_currentIndex == indexPath.row) return;
    
    _currentIndex = indexPath.row;
    
    NSString *fileName = _liveInfos[indexPath.row][@"playUrl"];
    NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
    NSURL *url = [NSURL URLWithString:path];
    
    [self.videoView setContentURL:url];
}

@end
